/**
 *
 */
package co.fitstart.payment.web.handler.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.demo2do.core.BusinessException;

import co.fitstart.payment.entity.app.App;
import co.fitstart.payment.entity.channel.Channel;
import co.fitstart.payment.web.handler.RequestValidateHandler;
import co.fitstart.payment.web.handler.SignatureHandler;

/**
 * @author lute
 */
@Component("requestValidateHandler")
public class RequestValidateHandlerImpl implements RequestValidateHandler {

    private static final Logger logger = LoggerFactory.getLogger(RequestValidateHandlerImpl.class);

    @Autowired
    private SignatureHandler signatureHandler;

    /* (non-Javadoc)
     * @see co.fitstart.payment.web.handler.RequestValidateHandler#validateRequestParameters(co.fitstart.payment.entity.app.App, co.fitstart.payment.entity.channel.Channel, java.util.Map)
     */
    @Override
    public void validateRequestParameters(App app, Channel channel, Map<String, String> parameters) throws BusinessException {
        if (app == null) {
            logger.error("RequestValidateHandlerImpl#validateRequestParameters - Can not find requesting app.");
            throw new BusinessException("Invalid app");
        }
        if (channel == null || channel.isDisabled()) {
            logger.error("RequestValidateHandlerImpl#validateRequestParameters - Can not find channel or channel is diabled.");
            throw new BusinessException("Invalid channel");
        }

        String signature = parameters.get("signature");
        boolean isSignatureValid = signatureHandler.checkAppSignature(app, signature, parameters, "signature");
        if (!isSignatureValid) {
            logger.error("RequestValidateHandlerImpl#validateRequestParameters - Signature validation fails.");
            throw new BusinessException("Invalid signature");
        }
    }

}
